package com.topscomm.main.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;

import com.topscomm.tap.security.TapSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class LocalSecurityExternalConfig extends TapSecurityConfigurerAdapter {
    /**
     * @param httpSecurity
     * @throws Exception
     * @description: configure(HttpSecurity
     *httpSecurity)返回的配置，用于在FilterSecurityInterceptor类中判断是否需要Spring
     * Security认证校验。
     * @author: zhangsui
     * @date: 2020年4月21日下午4:07:56
     * @modify:
     */
    @Override
    public void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity
                // 不创建会话
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().authorizeRequests()
                // hessian服务
                .antMatchers(("/pmHessian/**")).permitAll();
    }

    /**
     * @param web
     * @throws Exception
     * @description: 在org.springframework.security.web.FilterChainProxy.getFilters方法处，根据configure(WebSecurity
     * web)方法配置返回用于Spring Security校验的Filter
     * 比如：antMatchers(HttpMethod.POST,
     * "/auth/login")为ignoring()，则返回的用于Spring Security校验的Filter为空
     * 比如：当URL为/api/menus/build时，未在configure(WebSecurity
     * web)中配置，则会返回用于Spring Security校验的Filter。
     * WebSecurity的ingore是完全绕过了spring
     * security的所有filter，相当于不走spring security，而HttpSecurity
     * permitAll没有绕过spring security，其中包含了登录的以及匿名的。
     * HttpSecurity的permitAll，会给没有登录的用户适配一个AnonymousAuthenticationToken，设置到SecurityContextHolder，方便后面的filter可以统一处理authentication。
     * @author: zhangsui
     * @date: 2020年4月21日下午4:05:16
     * @modify:
     */
    @Override
    public void configure(WebSecurity web) throws Exception {
        // AuthenticationTokenFilter will ignore the below paths
        web.ignoring().antMatchers(HttpMethod.POST, "/auth/login").antMatchers(HttpMethod.GET, "/auth/login")
                // allow anonymous resource requests
                .and().ignoring().antMatchers(HttpMethod.GET, "/*.html", "/**/*.html", "/**/*.css", "/**/*.js");
    }
}
